import * as _ from "lodash"
import { camelCase, snakeCase } from "../case"
import { PageList } from "../data"
import httpClient from "../httpclient"
import { PaymentMethodType } from "./payment"
import { Withdrawal } from "./withdrawal"

export class RechargeQuery {

  private params = {}

  public page(page?: string | number): RechargeQuery {
    if (page) {
      this.params["page"] = page
    }
    return this
  }

  public limit(limit?: string | number): RechargeQuery {
    if (limit) {
      this.params["limit"] = limit
    }
    return this
  }

  public accountId(accountId?: string): RechargeQuery {
    this.params["account_id"] = accountId
    return this
  }

  public statuses(statuses?: string): RechargeQuery {
    if (statuses) {
      this.params["statuses"] = statuses
    }
    return this
  }

  public paymentMethods(paymentMethods?: string): RechargeQuery {
    if (paymentMethods) {
      this.params["payment_methods"] = paymentMethods
    }
    return this
  }

  public createdTimeStart(createdTimeStart?: string): RechargeQuery {
    if (createdTimeStart) {
      this.params["created_time_start"] = createdTimeStart
    }
    return this
  }

  public createdTimeEnd(createdTimeEnd?: string): RechargeQuery {
    if (createdTimeEnd) {
      this.params["created_time_end"] = createdTimeEnd
    }
    return this
  }

  public list(): Promise<PageList<Recharge>> {
    return httpClient.get("/v1/recharges", {
      params: this.params,
    }).then(({ data }) => data)
      .then(camelCase)
      .then(data => {
        return _.assign(new PageList<Recharge>(), data, {
          elements: _.map(data.elements, recharge => _.assign(new Recharge(), recharge)),
        })
      })
  }
}

export enum RechargeStatus {
  Pending = "pending",
  Canceled = "canceled",
  Succeeded = "succeeded",
  Failed = "failed",
}

export class Recharge {
  public id: string
  public accountId: string
  public currencyCode: string
  public amount: string
  public status: RechargeStatus
  public paymentMethod?: PaymentMethodType
}

export class RechargeServiceV1 {

  public static createRechargeQuery() {
    return new RechargeQuery()
  }

  public static createRecharge(recharge: Recharge): Promise<Recharge> {
    return httpClient.post(`/v1/recharges`, snakeCase(recharge))
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new Recharge(), data))
  }

  public static cancelRecharge(rechargeId: string): Promise<Withdrawal> {
    return httpClient.post(`/v1/recharges/${rechargeId}/cancel`)
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new Withdrawal(), data))
  }

  public static getRecharge(rechargeId: string): Promise<Recharge> {
    return httpClient.get(`/v1/recharges/${rechargeId}`)
      .then(({ data }) => data)
      .then(camelCase)
      .then(data => _.assign(new Recharge(), data))
  }
}
